from django.shortcuts import render, HttpResponse
from . import models, seria
from django.views import View
import uuid
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.mixins import ListModelMixin, CreateModelMixin, DestroyModelMixin, RetrieveModelMixin, \
    UpdateModelMixin
from . import auths

def index(request):
    return render(request, "index.html")

class LoginView(APIView):
    def get(self, request):
        return

    def post(self, request):
        user_dict = {"username": None, "token": None}
        username = request.data.get("username")
        password = request.data.get("password")
        user = models.UserInfo.objects.filter(
            username=username,
            password=password
        ).first()
        if user:
            token = uuid.uuid4()
            models.Token.objects.create(
                key=token,
                user=user
            )
            user_dict["username"] = username
            user_dict["token"] = token
            return Response(user_dict)
        else:
            return Response(user_dict)

class ArticleView(ListModelMixin, CreateModelMixin, DestroyModelMixin, RetrieveModelMixin, UpdateModelMixin,
                  GenericAPIView):
    queryset = models.Article.objects.all()
    serializer_class = seria.ArticleSeria
    authentication_classes = [auths.UserAuth, ]

    def get(self, request):
        return self.list(request)

    def post(self, request):
        print(request.data)
        return self.create(request)

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)


class UploadFile(View):
    def get(self, request):
        print("get-get-get")
        return render(request, "upload_file.html")
    def post(self, request):
        file_obj = request.FILES.get("file")
        print(file_obj)
        with open("files/01"+file_obj.name, "wb") as f:
            #方式1：
            # for i in file_obj.readlines():
            #     f.write(i)
            #方式2：
            for i in file_obj.chunks():
                f.write(i)
        return HttpResponse("ok")